package com.wwb.collect.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.ruoyi.common.core.utils.Md5Utils;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.wwb.collect.config.WwbProperties;
import com.wwb.collect.domain.enums.WwbApiUrlEnum;
import com.wwb.collect.service.IWwbCommonService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 微唯宝供应链公共方法
 * @Author: j.zh
 * @Date: 2024/6/6
 * @Version: 4.0.0
**/
@RequiredArgsConstructor
@Service
public class WwbCommonServiceImpl implements IWwbCommonService {

    private final RestTemplate restTemplate;

    @Resource
    WwbProperties wwbProperties;

    /**
     * @Description: 获取token
     * @Author: j.zh
     * @Date: 2024/6/6
     * @return
     * @Version: 4.0.0
    **/
    @Override
    public String getToken() {
        // 优先查询缓存
        if (RedisUtils.isExistsObject("wwbToken")){
            return RedisUtils.getCacheObject("wwbToken").toString();
        }
        // 不存在，重新获取
        String url = wwbProperties.getUrl() + "/api_" + wwbProperties.getVersion()
                + WwbApiUrlEnum.getToken.getApi();
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("app_id", wwbProperties.getAppId());
        requestMap.put("mobile", wwbProperties.getMobile());
        String timestamp = System.currentTimeMillis() + "";
        requestMap.put("timestamp", timestamp);
        // 配置签名：app_id + mobile + timestamp + app_secret 再用md5加密32位小写
        requestMap.put("sign", Md5Utils.encryptionMd5(
                wwbProperties.getAppId() + wwbProperties.getMobile()
                        + timestamp + wwbProperties.getAppSecret()));

        ResponseEntity<String> forEntity = restTemplate.postForEntity(
                url, requestMap, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        Integer errCode = jsonObject.getInteger("error_code");
        String accessToken = "";
        if (errCode == 0){
            JSONObject result = jsonObject.getJSONObject("result");
            accessToken = result.getString("access_token");
            String expireDateTime = result.getString("expire_date_time");
            long expireTime = result.getLongValue("expire_time");
//            RedisUtils.setCacheObject("wwbToken", accessToken, Duration.ofSeconds(expireTime));
            RedisUtils.setCacheObject("wwbToken", accessToken);
            RedisUtils.expire("wwbToken", expireTime);
        }
        return accessToken;
    }

}
